package com.fivefu.core.camera.services.impl;
import java.time.LocalDateTime;
import java.math.BigDecimal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.camera.constant.StatusEnum;
import com.fivefu.core.camera.entity.DbMonitorEventExamine;
import com.fivefu.core.camera.entity.DbMonitorEventReportForm;
import com.fivefu.core.camera.mapper.DbMonitorEventReportFormMapper;
import com.fivefu.core.camera.services.RegionService;
import com.fivefu.core.camera.services.DbMonitorEventExamineService;
import com.fivefu.core.camera.services.DbMonitorEventReportFormService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.camera.vo.response.MonthlySummaryPageList;
import com.fivefu.core.camera.vo.response.MonthlyUnqualifyEventBean;
import com.fivefu.core.skyeye.event.entity.DbAiScene;
import com.fivefu.core.skyeye.event.entity.DbAiSceneType;
import com.fivefu.core.skyeye.event.services.DbAiSceneService;
import com.fivefu.core.skyeye.event.services.DbAiSceneTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 事件报表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-09-26 17:04:37
 */
@Service
public class DbMonitorEventReportFormServiceImpl extends ServiceImpl<DbMonitorEventReportFormMapper, DbMonitorEventReportForm> implements DbMonitorEventReportFormService {

    @Autowired
    private DbAiSceneTypeService dbAiSceneTypeService;

    @Autowired
    private DbMonitorEventExamineService dbMonitorEventExamineService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private DbAiSceneService dbAiSceneService;

    /**
     *
     * 月度汇总列表
     * @param page
     * @param limit
     * @param year
     * @param month
     */
    @Override
    public Page<MonthlySummaryPageList> monthlySummaryList(Integer page, Integer limit, Integer year, Integer month) {
        Page<MonthlySummaryPageList> returnPage = new Page<>();

        List<DbMonitorEventReportForm> forms = new ArrayList<>();

        QueryWrapper<DbMonitorEventReportForm> wrapper = new QueryWrapper<>();
        wrapper.eq("year",year);
        wrapper.eq("month",month);

        if (page != null && limit != null){
            IPage iPage = new Page<>(page, limit);
            iPage = baseMapper.selectPage(iPage, wrapper);
            forms = iPage.getRecords();
            returnPage.setTotal(iPage.getTotal());
        }else {
            forms = baseMapper.selectList(wrapper);
            returnPage.setTotal(forms.size());
        }

        //月度汇总列表
        List<MonthlySummaryPageList> collect = forms.stream().map(l -> {
            MonthlySummaryPageList pageList = new MonthlySummaryPageList();
            pageList.setId(l.getId());
            //周期
            if (l.getYear() != null && l.getMonth() != null){
                String cycle = l.getYear() + "年" + l.getMonth() + "月";
                pageList.setCycle(cycle);
            }
            //场景类型
            if (StrUtils.isNotEmpty(l.getSceneCode())){
                DbAiScene dbAiScene = dbAiSceneService.querySceneByCode(l.getSceneCode());
                if (dbAiScene != null && StrUtils.isNotEmpty(dbAiScene.getCvType())){
                    DbAiSceneType dbAiSceneType = dbAiSceneTypeService.querySceneTypeByCvId(Integer.parseInt(dbAiScene.getCvType()));
                    if (dbAiSceneType != null){
                        pageList.setSceneType(dbAiSceneType.getCvName());
                    }
                }
            }
            pageList.setTotalNum(l.getTotalNum());
            pageList.setSuccessNum(l.getSuccessNum());
            pageList.setFailNum(l.getFailNum());
            pageList.setSuccessRate(l.getSuccessRate());
            pageList.setYear(l.getYear());
            pageList.setMonth(l.getMonth());
            pageList.setSceneCode(l.getSceneCode());
            return pageList;
        }).collect(Collectors.toList());

        returnPage.setRecords(collect);
        return returnPage;
    }

    /**
     *
     * 月度不合格事件列表
     * @param page
     * @param limit
     * @param eStime
     * @param eEtime
     */
    @Override
    public Page<MonthlyUnqualifyEventBean> monthlyUnqualifyEventList(Integer page, Integer limit, String eStime, String eEtime,Integer year,Integer month,String sceneCode) {
        IPage<MonthlyUnqualifyEventBean> iPage = new Page<>(page, limit);
        Page<MonthlyUnqualifyEventBean> beanPage = baseMapper.monthlyUnqualifyEventList(iPage,eStime,eEtime, StatusEnum.EXAMINE_UNHEGE.getStatusId(),year,month,sceneCode);

        beanPage.getRecords().stream().forEach(l->{
            if (StrUtils.isNotEmpty(l.getOrderAreaid())){
                l.setOrderAreaName(regionService.queryAreaNameByCode(l.getOrderAreaid()));
            }
        });
        return beanPage;
    }

/*    *//**
     *月度事件数据汇总(线程)
     *//*
    @Override
    public void monthlyEventDataSummary() {
        //1.查询所有事件表信息
        List<DbAiEvent> dbAiEvents = dbAiEventService.queryEventList();

        //2.通过事件表结束时间的年份进行分组
        Map<Integer, List<DbAiEvent>> yearMap = dbAiEvents.stream().collect(Collectors.groupingBy(l -> l.getEndTime().getYear()));

        //3.通过月进一步分组
        Set<Integer> integers = yearMap.keySet();
        for (Integer integer : integers) { //年
            List<DbAiEvent> eventList = yearMap.get(integer);
            Map<Integer, List<DbAiEvent>> monthMap = eventList.stream().collect(Collectors.groupingBy(l -> l.getEndTime().getMonth().getValue()));

            //4.通过场景编号在次分组
            Set<Integer> integers1 = monthMap.keySet();
            for (Integer integer1 : integers1) { //月
                List<DbAiEvent> events = monthMap.get(integer1);
                Map<String, List<DbAiEvent>> sceneCodeMap = events.stream().collect(Collectors.groupingBy(l -> l.getSceneId()));

                //遍历数据，添加报表信息
                Set<String> set1 = sceneCodeMap.keySet();
                for (String s : set1) { //场景编号
                    DbAiScene dbAiScene = dbAiSceneService.querySceneByCode(s);
                    if (dbAiScene != null){
                        DbMonitorEventReportForm reportForm = new DbMonitorEventReportForm();
                        reportForm.setCreatedTime(LocalDateTime.now());
                        reportForm.setUpdatedTime(LocalDateTime.now());

                        reportForm.setYear((long)integer);
                        reportForm.setMonth((long)integer1);
                        reportForm.setSceneCode(dbAiScene.getCode());
                        //该场景下所有事件
                        List<DbAiEvent> aiEventList = sceneCodeMap.get(s);
                        if (aiEventList != null){
                            reportForm.setTotalNum((long)aiEventList.size()); //事件总数
                        }

                        //通过事件ids查询符合所有符合条件的审核表信息
                        List<Long> list = aiEventList.stream().map(l -> l.getId()).collect(Collectors.toList());
                        List<DbMonitorEventExamine> examineList = dbMonitorEventExamineService.queryEventExaminesByEventIds(list);



                        reportForm.setExamineNum((long)examineList.size()); //审核事件数量
                        int fairLen = examineList.stream().filter(l -> l.getExamineStatus().equals("合格")).collect(Collectors.toList()).size();
                        int unFairLen = examineList.stream().filter(l -> l.getExamineStatus().equals("不合格")).collect(Collectors.toList()).size();

                        reportForm.setSuccessNum((long)fairLen);  //合格数量
                        reportForm.setFailNum((long)unFairLen); //不合格数量

                        //建立百分比格式化引用
                        //NumberFormat percent  = NumberFormat.getPercentInstance();
                        BigDecimal interestRate = new BigDecimal("0.00");
                        if (reportForm.getTotalNum() != null && reportForm.getSuccessNum() != null){
                            interestRate = new BigDecimal((double)reportForm.getSuccessNum()/reportForm.getTotalNum());
                        }
                        reportForm.setSuccessRate(interestRate); //识别正确率

                        //判断报表中是否有该数据，有则更新，无则添加
                        DbMonitorEventReportForm form = queryByYearMonthScene(integer, integer1, s);
                        if (form != null){
                            form.setUpdatedTime(LocalDateTime.now());
                            form.setTotalNum(reportForm.getTotalNum());
                            form.setExamineNum(reportForm.getExamineNum());
                            form.setSuccessNum(reportForm.getSuccessNum());
                            form.setFailNum(reportForm.getFailNum());
                            form.setSuccessRate(reportForm.getSuccessRate());
                            baseMapper.updateById(form);
                        }else {
                            baseMapper.insert(reportForm);
                        }
                    }
                }
            }
        }
    }*/

    /**
     *月度事件数据汇总(线程)
     */
    @Override
    public void monthlyEventDataSummary() {
        //1.查询所有审核表信息
        List<DbMonitorEventExamine> examineList = dbMonitorEventExamineService.queryEventExamineList(null);


        //2.通过审核表结束时间的年份进行分组
        Map<Integer, List<DbMonitorEventExamine>> yearMap = examineList.stream().collect(Collectors.groupingBy(l -> l.getExamineTime().getYear()));

        //3.通过月进一步分组
        Set<Integer> integers = yearMap.keySet();
        for (Integer integer : integers) { //年
            List<DbMonitorEventExamine> examines = yearMap.get(integer);

            //获取当前月份，过滤得到本月之前数据
            LocalDateTime nowTime = LocalDateTime.now();
            int nowMonth = nowTime.getMonth().getValue();
            int nowYear = nowTime.getYear();


            Map<Integer, List<DbMonitorEventExamine>> monthMap = examines.stream()
                    .filter(l->l.getExamineTime().getYear() < nowYear || l.getExamineTime().getMonth().getValue()<nowMonth)
                    .collect(Collectors.groupingBy(l -> l.getExamineTime().getMonth().getValue()));

            //4.以sceneCode为key进行遍历，添加数据
            Set<Integer> integers1 = monthMap.keySet();
            for (Integer integer1 : integers1) { //月
                List<DbMonitorEventExamine> eventExamines = monthMap.get(integer1);
                //sceneCode 为 key
                Map<String, List<DbMonitorEventExamine>> map = dbMonitorEventExamineService.sceneCodeAndEventExamineList(eventExamines);

                //遍历map，为报表添加数据
                Set<String> set = map.keySet();
                for (String s : set) {
                    DbMonitorEventReportForm reportForm = new DbMonitorEventReportForm();
                    reportForm.setCreatedTime(LocalDateTime.now());
                    reportForm.setUpdatedTime(LocalDateTime.now());
                    reportForm.setYear((long)integer);
                    reportForm.setMonth((long)integer1);
                    reportForm.setSceneCode(s);


                    List<DbMonitorEventExamine> dbMonitorEventExamines = map.get(s);
                    int UnqualifyLen = dbMonitorEventExamines.stream().filter(l -> l.getExamineStatus().equals(StatusEnum.EXAMINE_UNHEGE.getStatusId())).collect(Collectors.toList()).size();
                    int qualifyLen = dbMonitorEventExamines.stream().filter(l -> l.getExamineStatus().equals(StatusEnum.EXAMINE_HEGE.getStatusId())).collect(Collectors.toList()).size();

                    reportForm.setTotalNum((long)map.get(s).size());
                    reportForm.setExamineNum((long)map.get(s).size());
                    reportForm.setSuccessNum((long)qualifyLen);
                    reportForm.setFailNum((long)UnqualifyLen);
                    reportForm.setSuccessRate(new BigDecimal(0));

                    BigDecimal interestRate = new BigDecimal("0.00");
                    if (reportForm.getTotalNum() != null && reportForm.getSuccessNum() != null){
                        interestRate = new BigDecimal((double)reportForm.getSuccessNum()/reportForm.getTotalNum());
                    }
                    reportForm.setSuccessRate(interestRate); //识别正确率

                    //判断报表中是否有该数据，有则更新，无则添加
                    DbMonitorEventReportForm form = queryByYearMonthScene(integer, integer1, s);
                    if (form != null){
                        form.setUpdatedTime(LocalDateTime.now());
                        form.setTotalNum(reportForm.getTotalNum());
                        form.setExamineNum(reportForm.getExamineNum());
                        form.setSuccessNum(reportForm.getSuccessNum());
                        form.setFailNum(reportForm.getFailNum());
                        form.setSuccessRate(reportForm.getSuccessRate());
                        baseMapper.updateById(form);
                    }else {
                        baseMapper.insert(reportForm);
                    }
                }
            }
        }
    }

    /**
     *
     * 通过年 ， 月 ，场景编号 查询报表信息
     * @param year 年份
     * @param month 月份
     * @param sceneCode 场景编号
     */
    @Override
    public DbMonitorEventReportForm queryByYearMonthScene(Integer year, Integer month, String sceneCode) {
        QueryWrapper<DbMonitorEventReportForm> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (year != null){
            wrapper.eq("year",year);
        }
        if (month != null){
            wrapper.eq("month",month);
        }
        if (StrUtils.isNotEmpty(sceneCode)){
            wrapper.eq("scene_code",sceneCode);
        }
        List<DbMonitorEventReportForm> list = baseMapper.selectList(wrapper);
        return list.size() > 0? list.get(0):null;


    }
}
